package com.example.zx.theline.lyjh.pub;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zx.theline.R;
import com.example.zx.theline.lyjh.lyyjh.JhshActivity;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.ArrayList;
import java.util.List;

import GsonBean.ShyjhxqBean;
import GsonBean.SuccessBean;
import GsonBean.post.LjyyxJdjhbShdw;
import GsonBean.post.LjyyxSgxtbOpeartion;
import GsonBean.post.MySgbOpeartionZd;
import GsonBean.post.MyYdjdjhbInfo;
import Utils.DataUtils;
import Utils.DeviceUuidFactory;
import Utils.DictionariesUtil;
import Utils.MyToast;
import Utils.RefreshManager;
import app.MyApplication;
import base.BaseActivity;
import dialog.CustomDialog;
import greendao.UnitInformationDao;
import greendao.entity.UnitInformation;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Jianqi on 2017\8\18 0018.
 * 创建月计划流程项目主管部门/施工办设置流程页面
 */

@SuppressWarnings({"deprecation", "unchecked"})
public class YjhFlowSetActivity extends BaseActivity implements View.OnClickListener {
    //页面标题及自定义PopupWindow
    TextView leftTextView,rightTextView;
    TextView tv_textTitle;
    RelativeLayout rightLayout;
    private PopupWindow popupWindow;
    private SHListView popListView;
    private TextView popCancel, popConfirm, currentSelectValue;
    private EditText popEdit; //PopupWindow中的输入框
    private StringBuilder stringBuilder = new StringBuilder();
    private View line1, line2;
    private View view;
    private LayoutInflater inflater;
    //监理单位，建设单位，车务站段，设备管理单位，其它单位,审核处室，主管单位，主管单位值（公务处）
    private TextView selectJianli, selectJianshe, selectCwzd, selectSbgldw, selectQtdw, selectShenhe, zhuguan, zhuguanValue, btnCancel, btnConfirm;
    private EditText mYjEdit; //审核意见输入框
    //自定义Dialog
    private CustomDialog mCustomDialog;
    private TextView dialogTitle, dialogText, dialogCancel, dialogConfirm;
    //源数据集合及整理
    private List<ShyjhxqBean.InfoBean.ShdwListBean> mSourceList;
    private List<ShyjhxqBean.InfoBean.ShdwListBean> mJianliList = new ArrayList<>();
    private List<ShyjhxqBean.InfoBean.ShdwListBean> mJiansheList = new ArrayList<>();
    private List<ShyjhxqBean.InfoBean.ShdwListBean> mSpcsList = new ArrayList<>();
    //接收的标记
    private String flag;
    private String mCwFlag = "", mSbglFlag = "", mQitaFlag = "", mShcsFlag = ""; //恢复展示时的标记
    public static GsonBean.ShyjhxqBean ZsyjhxxShBean; //源数据
    private List<UnitInformation> mChangeList = new ArrayList<>(); //列表数据
    private List<UnitInformation> posListtest = new ArrayList<>(); //每次选择时的临时选中数据列表
    private MultipleAdapter mMultipleAdapter = new MultipleAdapter(); //适配列表数据的Adapter
    //上传封装的参数
    private int minLcstep = 0, midLcstep = 0, maxLcstep = 0; //审核步骤
    private StringBuilder shdwidBuilder = new StringBuilder(); //审核单位ID拼接
    private StringBuilder sbdwfzrBuilder = new StringBuilder(); //设备单位负责人拼接
    private StringBuilder shcsmcBuilder = new StringBuilder(); //审核处室名称拼接
    private StringBuilder shcsIdBuilder = new StringBuilder(); //审核处室ID拼接
    private List<UnitInformation> mSelectList = new ArrayList<>(); //列表展示的唯一数据集
    //多选项时用来记录选中的List集合
    private List<UnitInformation> mCwzdSelectList = new ArrayList<>();
    private List<UnitInformation> mSbglSelectList = new ArrayList<>();
    private List<UnitInformation> mQtdwSelectList = new ArrayList<>();
    private List<UnitInformation> mShcsSelectList = new ArrayList<>();
    /**
     * 2017/09/14 renkequan
     */
    private List<LjyyxJdjhbShdw> postShdwList = new ArrayList<>(); //已排序之后的要上传的List集合
    private List<LjyyxJdjhbShdw> shdwList = new ArrayList<>(); //用来存储要上传的数据的List集合
    private String tag = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yjh_flow_set);
        flag = getIntent().getStringExtra("flag");
        if (ZsyjhxxShBean == null) {
            MyApplication.ShowWaitDialog(this);
            MyApplication.setWaitDialogMsg("数据错误");
        } else {
            mSourceList = ZsyjhxxShBean.getInfo().getShdwList(); //从审核详情Bean类中获取源数据
        }
        InitView();
        InitListen();
        InitData();
    }

    @Override
    protected void InitView() { //初始化绑定控件
        leftTextView = (TextView) findViewById(R.id.leftTextView);
        rightTextView = (TextView) findViewById(R.id.rightTextView);
        tv_textTitle = (TextView) findViewById(R.id.centerTextView);

        mYjEdit = (EditText) findViewById(R.id.edit_yijian);
        selectJianli = (TextView) findViewById(R.id.tv_select_jldw);
        selectJianshe = (TextView) findViewById(R.id.tv_select_jsdw);
        selectShenhe = (TextView) findViewById(R.id.tv_select_shcs);
        line1 = findViewById(R.id.line_view1);
        line2 = findViewById(R.id.line_view2);
        zhuguan = (TextView) findViewById(R.id.tv_zhuguan);
        zhuguanValue = (TextView) findViewById(R.id.tv_zhuguan_value);
        btnCancel = (TextView) findViewById(R.id.btn_cancel);
        btnConfirm = (TextView) findViewById(R.id.btn_confirm);
        selectCwzd = (TextView) findViewById(R.id.autotv_cwzd);
        selectSbgldw = (TextView) findViewById(R.id.autotv_sbgldw);
        selectQtdw = (TextView) findViewById(R.id.autotv_qtdw);
        //初始化自定义Dialog
        mCustomDialog = new CustomDialog(this, R.layout.dialog_jldw, R.style.Theme_dialog);
        dialogTitle = (TextView) mCustomDialog.findViewById(R.id.tv_jldw_title);
        dialogText = (TextView) mCustomDialog.findViewById(R.id.tv_jldw_value);
        dialogCancel = (TextView) mCustomDialog.findViewById(R.id.btn_dialog_cancel);
        dialogConfirm = (TextView) mCustomDialog.findViewById(R.id.btn_dialog_confirm);
        mCustomDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    protected void InitData() { //页面数据初始化设置
        tv_textTitle.setText("月计划流程设置");
        rightTextView.setVisibility(View.GONE);
        //控制项目主管部门的显示与隐藏
        switch (flag) {
            case "xmzgbm": //项目主管部门点击进来
                zhuguan.setVisibility(View.GONE);
                zhuguanValue.setVisibility(View.GONE);
                line1.setVisibility(View.GONE);
                line2.setVisibility(View.GONE);
                break;
            case "sgb": //施工办点击进来
                zhuguan.setVisibility(View.VISIBLE);
                zhuguanValue.setVisibility(View.VISIBLE);
                line1.setVisibility(View.VISIBLE);
                line2.setVisibility(View.VISIBLE);
                break;
        }
        //遍历源数据集合,将源数据集合拆分成不同类型的小集合
        for (ShyjhxqBean.InfoBean.ShdwListBean list : mSourceList) {
            switch (list.getDwlb()) {
                case "jldw": //监理单位
                    mJianliList.add(list);
                    break;
                case "jsdw": //建设单位
                    mJiansheList.add(list);
                    break;
                case "spcs": //审批处室
                    mSpcsList.add(list);
                    break;
            }
        }
        //当监理单位、车务站段、其它单位源数据为空时,屏蔽其点击事件
        if (mJianliList.size() == 0) {
            selectJianli.setText("没有可指定的单位");
        }
        if (mSpcsList.size() > 0) {
            zhuguanValue.setText(mSpcsList.get(0).getDwmc()); //设置项目主管部门的值
        }
    }

    @Override
    protected void InitListen() {
        leftTextView.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        selectJianli.setOnClickListener(this);
        selectJianshe.setOnClickListener(this);
        selectCwzd.setOnClickListener(this);
        selectSbgldw.setOnClickListener(this);
        selectQtdw.setOnClickListener(this);
        selectShenhe.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
        dialogConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftTextView: //顶部返回按钮
                finish();
                break;
            case R.id.tv_select_jldw: //监理单位文本显示区
                if (mJianliList.size() > 0) {
                    dialogTitle.setText("指定监理单位");
                    dialogText.setText(mJianliList.get(0).getDwmc());
                    tag = "jldw";
                    mCustomDialog.setTag(tag);
                    mCustomDialog.show();
                }
                break;
            case R.id.tv_select_jsdw: //建设单位文本显示区
                if (mJiansheList.size() > 0) {
                    dialogTitle.setText("指定建设单位");
                    dialogText.setText(mJiansheList.get(0).getDwmc());
                    tag = "jsdw";
                    mCustomDialog.setTag(tag);
                    mCustomDialog.show();
                }
                break;
            case R.id.autotv_cwzd: //车务站段文本显示区
                popMutipleView(); //填充View
                mChangeList.clear();
                mChangeList.addAll(DictionariesUtil.getCwzdUnitList());
                tag = "cwzd";
                popupMultipleList();
                break;
            case R.id.autotv_sbgldw: //设备管理单位文本显示区
                popMutipleView();
                mChangeList.clear();
                mChangeList.addAll(DictionariesUtil.getSbgldwUnitList());
                tag = "sbgldw";
                popupMultipleList();
                break;
            case R.id.autotv_qtdw: //其它单位文本显示区
                popMutipleView();
                mChangeList.clear();
                mChangeList.addAll(DictionariesUtil.getQtdwUnitList());
                tag = "qtdw";
                popupMultipleList();
                break;
            case R.id.tv_select_shcs: //审核处室文本显示区
                popMutipleView();
                mChangeList.clear();
                mChangeList.addAll(DictionariesUtil.getJgcsUnitList());
                tag = "shcs";
                popupMultipleList();
                break;
            case R.id.btn_cancel: //页面总的取消按钮
                finish();
                break;
            case R.id.btn_confirm: //页面总的提交按钮
                if (shdwList.size() > 0) {
                    shdwList.clear();
                }
                checkCommit();
                break;
            case R.id.btn_dialog_cancel: //Dialog取消按钮
                mCustomDialog.dismiss();
                break;
            case R.id.btn_dialog_confirm: //Dialog确定按钮
                switch (mCustomDialog.getTag()) {
                    case "jldw":
                        selectJianli.setText(mJianliList.get(0).getDwmc());
                        selectJianli.setTextColor(Color.parseColor("#000000"));
                        break;
                    case "jsdw":
                        selectJianshe.setText(mJiansheList.get(0).getDwmc());
                        selectJianshe.setTextColor(Color.parseColor("#000000"));
                        break;
                    default:
                        break;
                }
                mCustomDialog.dismiss();
                break;
        }
    }

    //点击确定时的处理逻辑
    private void checkCommit() {
        if (mYjEdit.getText().length() > 0 && mYjEdit.getText().toString().trim().length() == 0) {
            Toast.makeText(this, "请不要输入空格", Toast.LENGTH_SHORT).show();
            return;
        }
        //首先判断页面上是否至少选择了一项：可能情况为：1、不为空全部显示要选择 2、1为空 3、3为空 4、5为空 5、13为空 6、15为空 7、35为空 8、135为空
        if (selectJianli.getText().toString().equals("点击选择监理单位") && selectJianshe.getText().toString().equals("点击选择建设单位") && selectCwzd.getText().toString().equals("请选择车务站段") && selectSbgldw.getText().toString().equals("请选择设备管理单位") && selectQtdw.getText().toString().equals("请选择其他单位") && selectShenhe.getText().toString().equals("请选择审核处室")) {
            MyToast.showToast("请至少选择一项");
        } else if (selectJianli.getText().toString().equals("没有可指定的单位") && selectJianshe.getText().toString().equals("点击选择建设单位") && selectCwzd.getText().toString().equals("请选择车务站段") && selectSbgldw.getText().toString().equals("请选择设备管理单位") && selectQtdw.getText().toString().equals("请选择其他单位") && selectShenhe.getText().toString().equals("请选择审核处室")) {
            MyToast.showToast("请至少选择一项");
        } else { //可以提交时
            //将之前选中的各个List添加到mSelectList中去
            mSelectList.addAll(mCwzdSelectList);
            mSelectList.addAll(mSbglSelectList);
            mSelectList.addAll(mQtdwSelectList);
            mSelectList.addAll(mShcsSelectList);
            //将源数据审核单位信息 转换成 发送信息 并加入发送信息list
            for (int i = 0; i < mSourceList.size(); i++) {
                shdwList.add(getSouceToPostBean(mSourceList.get(i)));
                if (!selectJianli.getText().toString().equals("没有可指定的单位") && !selectJianli.getText().toString().equals("点击选择监理单位")) {
                    if (mSourceList.get(i).getDwlb().equals("jldw")) {
                        shdwList.get(i).setSpzd("5");
                        minLcstep = Integer.parseInt("60");
                    }
                }
                if (!selectJianshe.getText().toString().equals("点击选择建设单位")) {
                    if (mSourceList.get(i).getDwlb().equals("jsdw")) {
                        shdwList.get(i).setSpzd("5");
                        minLcstep = Integer.parseInt("60");
                    }
                }
            }
            //对比发送信息list与选中单位信息list 如果是计划中原来存在的单位，则修改其标记位，否则新增
            //在单位实体的 parentid 暂存 单位类别 即 getParentId=“jldw”
            for (int i = 0; i < mSelectList.size(); i++) {
                for (int j = 0; j < shdwList.size(); j++) {
                    if (mSelectList.get(i).getLjyyxDwxxId().equals(shdwList.get(j).getDwId())
                            && mSelectList.get(i).getParentId().equals(shdwList.get(j).getDwlb())) {
                        shdwList.get(j).setSpzd("5");
                        switch (mSelectList.get(i).getParentId()) {
                            case "shcs":
                                midLcstep = Integer.parseInt("80");
                                break;
                            case "spcs":
                                maxLcstep = Integer.parseInt("90");
                                break;
                            default:
                                minLcstep = Integer.parseInt("60");
                                break;
                        }
                        break;
                    }
                    if (j + 1 == shdwList.size()) {
                        shdwList.add(getSelecetToPostBean(mSelectList.get(i)));
                    }
                }
            }
            //最后将list排序 施工单位，监理单位，建设单位，车务站段，设备管理单位，其他单位，审核处室 将list数据放入 PostShdwList
            for (int i = 0; i < shdwList.size(); i++) { //施工单位
                if (shdwList.get(i).getDwlb().equals("sgdw")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //监理单位
                if (shdwList.get(i).getDwlb().equals("jldw")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //建设单位
                if (shdwList.get(i).getDwlb().equals("jsdw")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //车务站段
                if (shdwList.get(i).getDwlb().equals("cwzd")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //设备管理单位
                if (shdwList.get(i).getDwlb().equals("sbgldw")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //其它单位
                if (shdwList.get(i).getDwlb().equals("qtdw")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //审核处室
                if (shdwList.get(i).getDwlb().equals("shcs")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    shcsIdBuilder.append(shdwList.get(i).getDwId()).append(","); //单独取审核处室ID拼接
                    postShdwList.add(shdwList.get(i));
                }
            }
            for (int i = 0; i < shdwList.size(); i++) { //审批处室
                if (shdwList.get(i).getDwlb().equals("spcs")) {
                    shdwidBuilder.append(shdwList.get(i).getDwId()).append(",");
                    postShdwList.add(shdwList.get(i));
                }
            }
            //封装外层数据对象，并且上传到服务端
            switch (flag) {
                case "xmzgbm":
                    LjyyxJdjhbShdw mXmzgCzjlBean = new LjyyxJdjhbShdw();
                    postShdwList.add(setRecordBean(mXmzgCzjlBean, mJiansheList.get(0), "xmzgbm"));
                    requestXmzgbmPost();
                    break;
                case "sgb":
                    LjyyxJdjhbShdw mSgbCzjlBean = new LjyyxJdjhbShdw();
                    shdwList.add(setRecordBean(mSgbCzjlBean, mJiansheList.get(0), "sgb"));
                    requestSgbPost();
                    break;
            }
        }
    }

    //施工办提交请求
    private void requestSgbPost() {
        //封装施工办的POST提交的数据对象
        MySgbOpeartionZd record = new MySgbOpeartionZd();
        //设置月计划号
        record.setBh(ZsyjhxxShBean.getInfo().getBh());
        //设置线路名称
        record.setXlmc(ZsyjhxxShBean.getInfo().getXlmc());
        //设置施工站名
        record.setXlzm(ZsyjhxxShBean.getInfo().getXlzm());
        //设置审核处室Id
        record.setShcsId(shcsIdBuilder.toString().substring(0, shcsIdBuilder.toString().length() - 1));
        //设置月计划审核步骤
        if (minLcstep == 60 && midLcstep == 0 && maxLcstep == 0) {
            record.setLcstep("60");
        } else if (minLcstep == 0 && midLcstep == 80 && maxLcstep == 0) {
            record.setLcstep("80");
        } else if (minLcstep == 0 && midLcstep == 0 && maxLcstep == 90) {
            record.setLcstep("90");
        } else if (minLcstep == 60 && midLcstep == 80 && maxLcstep == 0) {
            record.setLcstep("60");
        } else if (minLcstep == 0 && midLcstep == 80 && maxLcstep == 90) {
            record.setLcstep("80");
        } else if (minLcstep == 60 && midLcstep == 0 && maxLcstep == 90) {
            record.setLcstep("60");
        } else if (minLcstep == 60 && midLcstep == 80 && maxLcstep == 90) {
            record.setLcstep("60");
        }
        //设置审核批次
        record.setShzt(String.valueOf(Integer.parseInt(ZsyjhxxShBean.getInfo().getShzt()) + 1));
        //设置各审核单位ID拼接
        if (shdwidBuilder.length() > 0) {
            record.setShdwid(shdwidBuilder.toString().substring(0, shdwidBuilder.length() - 1)); //去掉最后一个逗号
        }
        //设置设备单位负责人
        if (sbdwfzrBuilder.length() > 0) {
            record.setSbdwfzr(ZsyjhxxShBean.getInfo().getSbdwfzr() + "," + sbdwfzrBuilder.toString().substring(0, sbdwfzrBuilder.length() - 1));
        } else { //没有新增的就直接使用原来的
            record.setSbdwfzr(ZsyjhxxShBean.getInfo().getSbdwfzr());
        }
        //设置审核处室名称
        if (shcsmcBuilder.length() > 0) {
            record.setShcsmc(ZsyjhxxShBean.getInfo().getShcsmc() + "," + shcsmcBuilder.toString().substring(0, shcsmcBuilder.length() - 1));
        } else {
            record.setShcsmc(ZsyjhxxShBean.getInfo().getShcsmc());
        }
        //设置审核单位List
        record.setShdwList(shdwList);
        //设置施工办重新指定操作记录信息对象
        LjyyxSgxtbOpeartion sgbOperationInfo = new LjyyxSgxtbOpeartion();
        sgbOperationInfo.setJdjhbBh(ZsyjhxxShBean.getInfo().getBh()); //月计划号
        sgbOperationInfo.setOpeartionType("4"); //施工办操作类型
        sgbOperationInfo.setOpeartionName("设置流程"); //施工办操作名称
        sgbOperationInfo.setOpeartionWorkername(MyApplication.getmLoginUser().getTrueName()); //登录用户真实姓名
        sgbOperationInfo.setOpeartionIp(DeviceUuidFactory.getDeviceId(this)); //施工办操作IP,这里传入的是一个唯一标识
        sgbOperationInfo.setDeleteFlag("N"); //删除标记
        sgbOperationInfo.setCjrId(MyApplication.getmLoginUser().getUserDisplayName()); //创建人ID
        sgbOperationInfo.setXgrId(MyApplication.getmLoginUser().getUserDisplayName()); //修改人ID
        record.setSgbOpeartionInfo(sgbOperationInfo);
        MyApplication.ShowWaitDialog(this);
        //提交所有数据
        NetWorkApi.postSgbSetFlowData(record, new BaseCallBack<SuccessBean>() {
                    @Override
                    public void Success(Call<SuccessBean> call, Response<SuccessBean> response) {
                        try {
                            responseData(response.body());
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<SuccessBean> call, Throwable t) {
                        MyToast.showFail();

                    }

                    @Override
                    public void onFinally() {

                    }
                }
        );
    }

    //项目主管部门提交请求
    private void requestXmzgbmPost() {
        //封装计划审核的POST提交的数据对象
        MyYdjdjhbInfo record = new MyYdjdjhbInfo();
        //设置月计划号
        record.setBh(ZsyjhxxShBean.getInfo().getBh());
        //设置线路名称
        record.setXlmc(ZsyjhxxShBean.getInfo().getXlmc());
        //设置施工站名
        record.setXlzm(ZsyjhxxShBean.getInfo().getXlzm());
        //设置审核处室Id
        record.setShcsId(shcsIdBuilder.toString().substring(0, shcsIdBuilder.toString().length() - 1));
        //设置月计划审核步骤
        if (minLcstep == 60 && midLcstep == 0 && maxLcstep == 0) {
            record.setLcstep("60");
        } else if (minLcstep == 0 && midLcstep == 80 && maxLcstep == 0) {
            record.setLcstep("80");
        } else if (minLcstep == 0 && midLcstep == 0 && maxLcstep == 90) {
            record.setLcstep("90");
        } else if (minLcstep == 60 && midLcstep == 80 && maxLcstep == 0) {
            record.setLcstep("60");
        } else if (minLcstep == 0 && midLcstep == 80 && maxLcstep == 90) {
            record.setLcstep("80");
        } else if (minLcstep == 60 && midLcstep == 0 && maxLcstep == 90) {
            record.setLcstep("60");
        } else if (minLcstep == 60 && midLcstep == 80 && maxLcstep == 90) {
            record.setLcstep("60");
        }
        //设置审核批次
        record.setShzt(String.valueOf(Integer.parseInt(ZsyjhxxShBean.getInfo().getShzt()) + 1));
        //设置各审核单位ID拼接
        if (shdwidBuilder.length() > 0) {
            record.setShdwid(shdwidBuilder.toString().substring(0, shdwidBuilder.length() - 1)); //去掉最后一个逗号
        }
        //设置设备单位负责人
        if (sbdwfzrBuilder.length() > 0) {
            record.setSbdwfzr(ZsyjhxxShBean.getInfo().getSbdwfzr() + "," + sbdwfzrBuilder.toString().substring(0, sbdwfzrBuilder.length() - 1));
        } else { //没有新增的直接上传原来的
            record.setSbdwfzr(ZsyjhxxShBean.getInfo().getSbdwfzr());
        }
        //设置审核处室名称
        if (shcsmcBuilder.length() > 0) {
            record.setShcsmc(ZsyjhxxShBean.getInfo().getShcsmc() + "," + shcsmcBuilder.toString().substring(0, shcsmcBuilder.length() - 1));
        } else {
            record.setShcsmc(ZsyjhxxShBean.getInfo().getShcsmc());
        }
        //设置审核单位List
        record.setShdwList(postShdwList);
        MyApplication.ShowWaitDialog(this);
        //提交所有数据
        NetWorkApi.postSetFlowData(record, new BaseCallBack<SuccessBean>() {
                    @Override
                    public void Success(Call<SuccessBean> call, Response<SuccessBean> response) {
                        try {
                            responseData(response.body());
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                    }

                    @Override
                    public void Failure(Call<SuccessBean> call, Throwable t) {
                        MyToast.showFail();

                    }

                    @Override
                    public void onFinally() {

                    }
                }
//                new ObjectHttpResponseHandler(this, SuccessBean.class) {
//            @Override
//            public void Success(int i, Header[] headers, Object object) {
//                try {
//                    responseData(object);
//                } catch (Exception e){
//                    MyToast.showFail();
//
//                }
//
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//                MyApplication.HideWaitDialog();
//            }
//        }
        );
    }

    //处理响应数据结果
    private void responseData(SuccessBean mSuccessBean) {
        if (mSuccessBean.getMsg().equals("success")) {
            MyToast.showToast("设置成功");
            RefreshManager.Sgyjh.RefreshShyjh();
            RefreshManager.Sgyjh.RefreshShywc();
            RefreshManager.Sgyjh.RefreshSpywc();
            startActivity(new Intent(YjhFlowSetActivity.this, JhshActivity.class));
        } else {
            Toast.makeText(YjhFlowSetActivity.this, mSuccessBean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    //更新之前选中的列表
    private void notifyPopList(List<UnitInformation> list) {
        switch (tag) {
            case "cwzd":
                mCwFlag = "true";
                break;
            case "sbgldw":
                mSbglFlag = "true";
                break;
            case "qtdw":
                mQitaFlag = "true";
                break;
            case "shcs":
                mShcsFlag = "true";
                break;
        }
        stringBuilder.setLength(0);
        posListtest.clear();
        posListtest.addAll(list);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < mChangeList.size(); j++) {
                if (list.get(i).getLjyyxDwxxId().equals(mChangeList.get(j).getLjyyxDwxxId())) {
                    mChangeList.get(j).setIsSelected(true);
                    stringBuilder.append(mChangeList.get(j).getLjyyxDwxxName()).append(",");
                }
            }
        }
        if (stringBuilder.length() > 0) {
            currentSelectValue.setText(stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1));
        }
        mMultipleAdapter.notifyDataSetChanged();
    }

    //填充PopupWindow中的数据
    private void popupMultipleList() {
        for (UnitInformation list : mChangeList) {
            list.setIsSelected(false);
        }
        popListView.setAdapter(mMultipleAdapter);
//        恢复之前选中的ListView的Item项
        switch (tag) {
            case "cwzd":
                if (!selectCwzd.getText().toString().equals("请选择车务站段")) {
                    notifyPopList(mCwzdSelectList);
                } else {
                    posListtest.clear();
                }
                break;
            case "sbgldw":
                if (!selectSbgldw.getText().toString().equals("请选择设备管理单位")) {
                    notifyPopList(mSbglSelectList);
                } else {
                    posListtest.clear();
                }
                break;
            case "qtdw":
                if (!selectQtdw.getText().toString().equals("请选择其他单位")) {
                    notifyPopList(mQtdwSelectList);
                } else {
                    posListtest.clear();
                }
                break;
            case "shcs":
                if (!selectShenhe.getText().toString().equals("请选择审核处室")) {
                    notifyPopList(mShcsSelectList);
                } else {
                    posListtest.clear();
                }
                break;
        }
        //ListView每一项的点击事件
        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (stringBuilder.length() > 0) { //防止累加填充
                    stringBuilder.setLength(0);
                }
                mChangeList.get(position).setIsSelected(!mChangeList.get(position).getIsSelected());
                mMultipleAdapter.notifyDataSetChanged();
                if (mChangeList.get(position).getIsSelected()) { //列表项选中，将对应的下标添加到集合中
                    UnitInformation un = new UnitInformation();
                    DataUtils.converJavaBean(un, mChangeList.get(position)); //将选中Item的属性赋值给新的对象
                    un.setParentId(tag);
                    posListtest.add(un);
                } else { //取消选中时，将对应的下标从集合中移除
                    for (int i = 0; i < posListtest.size(); i++) {
                        if (posListtest.get(i).getLjyyxDwxxId().equals(mChangeList.get(position).getLjyyxDwxxId())) {
                            posListtest.remove(i);
                        }
                    }
                }
                //将当前选中的内容显示到顶部文本控件上
                if (posListtest.size() > 0) { //有选中内容时，以逗号分隔显示到顶部控件上
                    for (int i = 0; i < posListtest.size(); i++) {
                        stringBuilder.append(posListtest.get(i).getLjyyxDwxxName()).append(",");
                    }
                    currentSelectValue.setText(stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1));
                } else { //没有选中的内容时，不显示内容
                    currentSelectValue.setText("");
                }
            }
        });
        //取消按钮事件
        popCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //确定按钮事件
        popConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (tag) {
                    case "cwzd":
                        displayResult(selectCwzd, mCwFlag, mCwzdSelectList);
                        break;
                    case "sbgldw":
                        displayResult(selectSbgldw, mSbglFlag, mSbglSelectList);
                        break;
                    case "qtdw":
                        displayResult(selectQtdw, mQitaFlag, mQtdwSelectList);
                        break;
                    case "shcs":
                        displayResult(selectShenhe, mShcsFlag, mShcsSelectList);
                        break;
                }
                popupWindow.dismiss();
                posListtest.clear(); //点击确定时将当前集合清除，防止下次点击的时候重复添加上一次的内容
                stringBuilder.setLength(0); //将当前stringBuilder中的内容清空
            }
        });
        //输入框中数据变化时，下方数据列表实时变化
        popEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                switch (tag) {
                    case "cwzd":
                        refreshMultipleList(s, UnitInformationDao.Properties.LjyyxDwxxType.like("%" + DictionariesUtil.CWZD + "%"));
                        break;
                    case "sbgldw":
                        refreshMultipleList(s, UnitInformationDao.Properties.LjyyxDwxxType.like("%" + DictionariesUtil.SBGLDW + "%"));
                        break;
                    case "qtdw":
                        refreshMultipleList(s, UnitInformationDao.Properties.LjyyxDwxxType.like("%" + DictionariesUtil.QTDW + "%"));
                        break;
                    case "shcs":
                        refreshMultipleList(s, UnitInformationDao.Properties.LjyyxDwxxType.like("%" + DictionariesUtil.JGCS + "%"));
                        break;
                }
            }
        });
    }

    //显示文本以及取选中集合
    private void displayResult(TextView selectText, String biaozhi, List<UnitInformation> selectList) {
        if (stringBuilder.length() > 0) {
            selectText.setText(stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1));
            selectText.setTextColor(Color.parseColor("#000000"));
        } else {
            switch (tag) {
                case "cwzd":
                    selectText.setText("请选择车务站段");
                    break;
                case "sbgldw":
                    selectText.setText("请选择设备管理单位");
                    break;
                case "qtdw":
                    selectText.setText("请选择其他单位");
                    break;
                case "shcs":
                    selectText.setText("请选择审核处室");
                    break;
            }
            selectText.setTextColor(Color.parseColor("#7f7f7f"));
        }
        if (biaozhi.equals("true")) {
            //先把之前的全部删除掉，再往里面添加
            selectList.clear();
            selectList.addAll(posListtest);
        } else {
            selectList.addAll(posListtest);
        }
    }

    //输入条件进行筛选并展示新数据列表
    private void refreshMultipleList(Editable s, WhereCondition conditions1) {
        switch (tag) {
            case "cwzd":
                selectList(s, DictionariesUtil.getCwzdUnitList(), conditions1);
                break;
            case "sbgldw":
                selectList(s, DictionariesUtil.getSbgldwUnitList(), conditions1);
                break;
            case "qtdw":
                selectList(s, DictionariesUtil.getQtdwUnitList(), conditions1);
                break;
            case "shcs":
                selectList(s, DictionariesUtil.getJgcsUnitList(), conditions1);
                break;
        }
    }

    //筛选数据列表展示
    private void selectList(Editable s, List<UnitInformation> list, WhereCondition conditions1) {
        mChangeList.clear();
        if (s.length() == 0) {
            mChangeList.addAll(list);
        } else {
            mChangeList = MyApplication.getDaoSession().getUnitInformationDao().queryBuilder()
                    .where(conditions1, UnitInformationDao.Properties.LjyyxDwxxName.like("%" + popEdit.getText().toString() + "%")).list();
        }
        mMultipleAdapter.notifyDataSetChanged();
    }

    //加载布局
    @SuppressLint("InflateParams")
    private void popMutipleView() {
        inflater = LayoutInflater.from(this);
        view = inflater.inflate(R.layout.popup_window_list, null);
        setArguments();
        popListView = (SHListView) view.findViewById(R.id.multiple_list);
        popCancel = (TextView) view.findViewById(R.id.pop_cancel);
        popConfirm = (TextView) view.findViewById(R.id.pop_confirm);
        popEdit = (EditText) view.findViewById(R.id.pop_edit);
        currentSelectValue = (TextView) view.findViewById(R.id.current_select_value);
    }

    //多条数据的适配器
    private class MultipleAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mChangeList.size();
        }

        @Override
        public Object getItem(int position) {
            return mChangeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(YjhFlowSetActivity.this).inflate(R.layout.item_popwindow_multiple, parent, false);
                holder = new ViewHolder();
                holder.textView = (TextView) convertView.findViewById(R.id.multiple_text);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.multiple_checkbox);
                holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.select_layout);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (mChangeList.get(position).getIsSelected()) {
                holder.checkBox.setChecked(true);
                holder.linearLayout.setBackgroundColor(Color.parseColor("#f47979"));
            } else {
                holder.linearLayout.setBackgroundColor(Color.TRANSPARENT);
                holder.checkBox.setChecked(false);
            }
            holder.textView.setText(mChangeList.get(position).getLjyyxDwxxName());
            return convertView;
        }

        class ViewHolder {
            TextView textView;
            CheckBox checkBox;
            LinearLayout linearLayout;
        }
    }

    //设置PopupWindow的参数
    @SuppressLint("InflateParams")
    @SuppressWarnings("deprecation")
    public void setArguments() {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        popupWindow = new PopupWindow(view, 2 * width / 3, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.8f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        //这里传入的是当前所在页面的布局
        popupWindow.showAtLocation(inflater.inflate(R.layout.activity_yjh_flow_set, null), Gravity.RIGHT, 0, 0);
    }

    //将源数据list对象转换成post类型对象
    public LjyyxJdjhbShdw getSouceToPostBean(ShyjhxqBean.InfoBean.ShdwListBean mInfo) {
        LjyyxJdjhbShdw mNewBean = new LjyyxJdjhbShdw();
        mNewBean.setJdjhbBh(mInfo.getJdjhbBh());
        mNewBean.setDwId(mInfo.getDwId());
        mNewBean.setDwmc(mInfo.getDwmc());
        mNewBean.setDwlb(mInfo.getDwlb());
        mNewBean.setShsx(mInfo.getShsx());
        mNewBean.setShzt(String.valueOf(Integer.parseInt(ZsyjhxxShBean.getInfo().getShzt()) + 1));
        if (mInfo.getDwlb().equals("spcs") && Integer.parseInt(mInfo.getShsx()) < 100) {
            mNewBean.setSpzd("5");
        } else {
            mNewBean.setSpzd("0");
        }
        mNewBean.setShlb(mInfo.getShlb());
        mNewBean.setDylb(mInfo.getDylb());
        mNewBean.setDeleteFlag(mInfo.getDeleteFlag());
        mNewBean.setCjrId(mInfo.getCjrId());
        mNewBean.setCjrq(mInfo.getCjrq());
        return mNewBean;
    }

    //将选中单位对象转换成post类型对象
    public LjyyxJdjhbShdw getSelecetToPostBean(UnitInformation mInfo) {
        LjyyxJdjhbShdw mNewBean = new LjyyxJdjhbShdw();
        mNewBean.setJdjhbBh(ZsyjhxxShBean.getInfo().getBh());
        mNewBean.setDwId(mInfo.getLjyyxDwxxId());
        mNewBean.setDwmc(mInfo.getLjyyxDwxxName());
        mNewBean.setDwlb(mInfo.getParentId());
        sbdwfzrBuilder.append(mInfo.getLjyyxDwxxName()).append(","); //新增设备单位负责人
        switch (mInfo.getParentId()) {
            case "sgdw":
                mNewBean.setShlb("1");
                break;
            case "shcs":
                mNewBean.setShsx("80");
                mNewBean.setShlb("3");
                midLcstep = Integer.parseInt("80"); //设置审核步骤
                shcsmcBuilder.append(mInfo.getLjyyxDwxxName()).append(","); //新增审核处室名称
                break;
            case "spcs":
                mNewBean.setShsx("90");
                mNewBean.setShlb("4");
                maxLcstep = Integer.parseInt("90");
                break;
            default:
                mNewBean.setShsx("60");
                mNewBean.setShlb("2");
                minLcstep = Integer.parseInt("60");
                break;
        }
        mNewBean.setShzt(String.valueOf(Integer.parseInt(ZsyjhxxShBean.getInfo().getShzt()) + 1));
        mNewBean.setSpzd("5");
        mNewBean.setDylb("Y");
        mNewBean.setDeleteFlag("N");
        mNewBean.setCjrId(MyApplication.getmLoginUser().getUserDisplayName());
        return mNewBean;
    }

    //设置操作记录的Bean类
    private LjyyxJdjhbShdw setRecordBean(LjyyxJdjhbShdw mNewBean, ShyjhxqBean.InfoBean.ShdwListBean mSourceBean, String flag) {
        mNewBean.setJdjhbBh(mSourceBean.getJdjhbBh());
        mNewBean.setDwId(MyApplication.getmLoginUser().getUserUnitId());
        mNewBean.setDwmc(MyApplication.getmLoginUser().getUserUnitName());
        if (flag.equals("sgb")) { //当是施工办的时候
            mNewBean.setDwlb("sgb");
            mNewBean.setShsx("140");
            mNewBean.setShlb("5");
        } else if (flag.equals("xmzgbm")) { //当是主管部门的时候
            mNewBean.setDwlb("spcs");
            mNewBean.setShsx("110");
            mNewBean.setShlb("4");
        }
        mNewBean.setShzt(String.valueOf(Integer.parseInt(ZsyjhxxShBean.getInfo().getShzt()) + 1));
        mNewBean.setSpzd("0");
        mNewBean.setDylb("Y");
        mNewBean.setDeleteFlag("N");
        mNewBean.setCjrId(MyApplication.getmLoginUser().getUserDisplayName());
        mNewBean.setSftg("ZD");
        mNewBean.setShyj(mYjEdit.getText().toString());
        mNewBean.setShrlogin(MyApplication.getmLoginUser().getUserDisplayName());
        mNewBean.setShrname(MyApplication.getmLoginUser().getTrueName());
        mNewBean.setShrphone(MyApplication.getmLoginUser().getUserMobilephone());
        return mNewBean;
    }

}
